package com.meko.tms.core.schedule;

import com.alibaba.druid.util.StringUtils;

import com.meko.tms.core.access.AbstractAccessData;
import com.meko.tms.core.mapper.CronMapper;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

public abstract class AbstractScheduleConfig implements SchedulingConfigurer {

    @SuppressWarnings("all")
    CronMapper cronMapper;
    AbstractAccessData abstractAccessData;

    protected AbstractScheduleConfig(CronMapper cronMapper, AbstractAccessData abstractAccessData) {
        this.cronMapper = cronMapper;
        this.abstractAccessData = abstractAccessData;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                abstractAccessData::accessData,
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                        cron = "0/1 * * * * ?";
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
